#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QPushButton>
#include <QFileDialog>
#include <QTextStream>

#include "dialog_newlistfile.h"
#include "ui_dialog_newlistfile.h"
#include "dialog_set.h"
#include "ui_dialog_set.h"
#include "dialog_about.h"
#include "ui_dialog_about.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{

    ui->setupUi(this);

    newListFile = new Dialog_newListFile(this);

    isUntitled = true;

    curFile = tr("未命名.apro");

    setWindowTitle(curFile);

    //new QListWidgetItem(tr("Oak"), ui->listWidget);
         //ui->tableWidget->setHorizontalHeaderLabels(QStringList()<<"name"<<"age");
       ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);  //整行选中的方式
     //  ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);   //禁止修改
       ui->tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);  //设置为可以选中单个
       ui->tableWidget->verticalHeader()->setVisible(false);   //隐藏列表头
       ui->tableWidget->setColumnWidth(2,360);

       ui->tableWidget->setItem(0,0,new QTableWidgetItem("21"));
       ui->tableWidget->setItem(0,1,new QTableWidgetItem("1"));
       ui->tableWidget->setItem(0,2,new QTableWidgetItem("12342345"));


       ui->tableWidget->selectRow(1);
       FileIndexStartAddr = "0";
       FileDataStartAddr = "1024";
       ui->label_fileindexaddr->setText(FileIndexStartAddr);
       ui->label_filedataaddr->setText(FileDataStartAddr);
       DialogFileaddr = new Dialog_SET(this);
       Dialogabout = new Dialog_about(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}



void MainWindow::on_action_triggered()
{
    if (maybeSave()) {
        isUntitled = true;
        curFile = tr("未命名.apro");
        setWindowTitle(curFile);

        ui->tableWidget->clear();
        ui->tableWidget->setRowCount(0);
        FileIndexStartAddr = "0";
        FileDataStartAddr = "1024";
    }
}

bool MainWindow::maybeSave()
{
   // 如果文档被更改了
    /*
if (ui->textEdit->document()->isModified()) {
// 自定义一个警告对话框
       QMessageBox box;
       box.setWindowTitle(tr("警告"));
       box.setIcon(QMessageBox::Warning);
       box.setText(curFile + tr(" 尚未保存，是否保存？"));
       QPushButton *yesBtn = box.addButton(tr("是(&Y)"),
                        QMessageBox::YesRole);
       box.addButton(tr("否(&N)"), QMessageBox::NoRole);
       QPushButton *cancelBut = box.addButton(tr("取消"),
                        QMessageBox::RejectRole);
       box.exec();
       if (box.clickedButton() == yesBtn)
            return save();
       else if (box.clickedButton() == cancelBut)
            return false;
   }*/
   // 如果文档没有被更改，则直接返回true
   return true;
}


bool MainWindow::save()
{
   if (isUntitled) {
       return saveAs();
   } else {
       return saveFile(curFile);
   }
}


bool MainWindow::saveAs()
{
   QString fileName = QFileDialog::getSaveFileName(this, tr("另存为"),curFile,tr("*.apro"));
   if (fileName.isEmpty()) return false;

   QString temp=fileName.right(5);
   if(temp != ".apro")
       fileName += ".apro";
   return saveFile(fileName);
}


bool MainWindow::saveFile(const QString &fileName)
{
    QFile file(fileName);
    int i;
    if (!file.open(QFile::WriteOnly | QFile::Text)) {

        // %1和%2分别对应后面arg两个参数，/n起换行的作用
        QMessageBox::warning(this, tr("Filemake"),
                             tr("无法写入文件 %1：/n %2")
                             .arg(fileName).arg(file.errorString()));
        return false;
    }
    /*  QTextStream out(&file);
   // 鼠标指针变为等待状态
   QApplication::setOverrideCursor(Qt::WaitCursor);
   out << ui->textEdit->toPlainText();
   // 鼠标指针恢复原来的状态
   QApplication::restoreOverrideCursor();*/

    QByteArray tmp;
    //FileIndexStartAddr = "256";
    tmp.fill(0xff,FileIndexStartAddr.toLongLong());
    //FILEMAKE-PROJECT-01232-151554
    QString str;

    str = "FILEMAKE-PROJECT-"+FileIndexStartAddr+"-"+FileDataStartAddr;
    if(str.right(1)!="\n")
        str+="\n";
    file.write(str.toLatin1());
    for(i =0 ;i<ui->tableWidget->rowCount();i++){
        str = "FILEMAKE-"+ui->tableWidget->item(i,0)->text()+"-"+ui->tableWidget->item(i,1)->text()+"-"
                +ui->tableWidget->item(i,2)->text();
        if(str.right(1)!="\n")
            str+="\n";
        file.write(str.toLatin1());
    }
    isUntitled = false;
    // 获得文件的标准路径
    curFile = QFileInfo(fileName).canonicalFilePath();
    setWindowTitle(curFile);
    return true;
}


bool MainWindow::loadFile(const QString &fileName)
{
    QFile file(fileName); // 新建QFile对象
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("多文档编辑器"),
                             tr("无法读取文件 %1:\n%2.")
                             .arg(fileName).arg(file.errorString()));
        return false; // 只读方式打开文件，出错则提示，并返回false
    }

    ui->tableWidget->clear();
    ui->tableWidget->setRowCount(0);

    QByteArray line = file.readLine();
    QString str(line);
    QStringList list1 = str.split("-");
    if(list1.at(0) != "FILEMAKE")
        return false;
    if(list1.at(1) != "PROJECT")
        return false;

    FileIndexStartAddr = list1.at(2);
    FileDataStartAddr = list1.at(3);
    ui->label_fileindexaddr->setText(FileIndexStartAddr);
    ui->label_filedataaddr->setText(FileDataStartAddr);

    while(!file.atEnd()) {
        QByteArray line = file.readLine();
        QString str(line);
        QStringList list1 = str.split("-");
        if(list1.count()!=4)
            return false;
        if(list1.at(0) != "FILEMAKE")
            continue;
        fileaddlist(list1.at(1),list1.at(2),list1.at(3));

    }




    // 设置当前文件
    curFile = QFileInfo(fileName).canonicalFilePath();
    setWindowTitle(curFile);
    return true;
}




void MainWindow::on_action_2_triggered()
{
    if (maybeSave()) {
        QString fileName = QFileDialog::getOpenFileName(this,tr("打开"),curFile,tr("*.apro"));
    //    QString fileName = QFileDialog::getOpenFileName(this);

           // 如果文件名不为空，则加载文件
           if (!fileName.isEmpty()) {
                loadFile(fileName);


           }
       }
}

void MainWindow::on_action_4_triggered()
{
    //on_action_Close_triggered();
       qApp->quit();
}

void MainWindow::on_action_3_triggered()
{
     save();
}

void MainWindow::on_actionLiangcun_triggered()
{
    saveAs();
}

void MainWindow::on_pb_addfile_clicked()
{

    newListFile->show();
    /* quint16 index;

     QString fileName = QFileDialog::getOpenFileName(this,tr("打开"), ".",tr("*.mp3;;**.*"));
    QFile file(fileName); // 新建QFile对象
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("多文档编辑器"),
                              tr("无法读取文件 %1:\n%2.")
                              .arg(fileName).arg(file.errorString()));
        return ; // 只读方式打开文件，出错则提示，并返回false
    }






    index = ui->tableWidget->rowCount();
    ui->tableWidget->insertRow(index);
    ui->tableWidget->setItem(index,0,new QTableWidgetItem("lisi"));
    ui->tableWidget->setItem(index,1,new QTableWidgetItem("20"));
    ui->tableWidget->setItem(index,2,new QTableWidgetItem(fileName));*/


}


bool MainWindow::CheckID(QString newid)
{
    int i;
    int index;
    index = ui->tableWidget->rowCount();
    for(i=0;i<index;i++)
    {
        if(newid == ui->tableWidget->item(i,0)->text()){
            QMessageBox::warning(this, tr("提示"),tr("ID号已经使用，请更换ID号"));
            return 0;
        }

    }


    return 1;

}

void MainWindow::fileaddlist(QString ID,QString addr,QString fileName)
{
    int i;
    int index;
    index = ui->tableWidget->rowCount();

    ui->tableWidget->insertRow(index);
    ui->tableWidget->setItem(index,0,new QTableWidgetItem(ID));
    ui->tableWidget->setItem(index,1,new QTableWidgetItem(addr));
    ui->tableWidget->setItem(index,2,new QTableWidgetItem(fileName));


}

void MainWindow::on_pb_delfile_clicked()
{
    QTableWidgetItem * item = ui->tableWidget->currentItem();
    if(item==Q_NULLPTR)return;
    ui->tableWidget->removeRow(item->row());
}

void MainWindow::setFileAddr(QString indexaddr , QString dataaddr)
{
    FileIndexStartAddr = indexaddr;
    FileDataStartAddr = dataaddr;
    ui->label_fileindexaddr->setText(FileIndexStartAddr);
    ui->label_filedataaddr->setText(FileDataStartAddr);
}

void MainWindow::on_pushButton_clicked()
{
    DialogFileaddr->show();
}

void MainWindow::on_pb_build_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("另存为"),"FileData",tr("*.bin"));
    if (fileName.isEmpty()) return;

    QString temp=fileName.right(4);
    if(temp != ".bin")
        fileName += ".bin";

    QFile file(fileName); // 新建QFile对象
   QFile bulidfile("bulid.o"); // 新建QFile对象

   bulidfile.remove();

    if (!bulidfile.open(QFile::ReadWrite | QFile::Text)) {

        // %1和%2分别对应后面arg两个参数，/n起换行的作用
        QMessageBox::warning(this, tr("Filemake"),tr("无法写入文件"));
        return ;
    }

    if (!file.open(QFile::WriteOnly | QFile::Text)) {

        // %1和%2分别对应后面arg两个参数，/n起换行的作用
        QMessageBox::warning(this, tr("Filemake"),
                             tr("无法写入文件 %1：/n %2")
                             .arg(fileName).arg(file.errorString()));
        return ;
    }
    QByteArray tmp;
    QString rowdata;
    char buf[256];
    int id;
    int i;
    unsigned long addroffest = 0;

//FileIndexStartAddr = "256";

    tmp.fill(0xff,FileDataStartAddr.toLongLong());
    file.write(tmp.data());
    tmp.clear();
    addroffest = FileIndexStartAddr.toLongLong();
    file.seek(addroffest);

    for(i=0;i<ui->tableWidget->rowCount();i++){

        rowdata =ui->tableWidget->item(i,0)->text();
        id=rowdata.toInt();
        buf[0]= (id>>8)&0x000000ff;
        buf[1]= id&0x000000ff;
        file.write(buf,2);

        QFile Tempfile(ui->tableWidget->item(i,2)->text()); // 新建QFile对象

        if (!Tempfile.open(QFile::ReadOnly )) {
            QMessageBox::warning(this, tr("Filemake"),tr("无法打开数据文件"));
            return ;
        }


        buf[0]= (addroffest>>24)&0x000000ff;
        buf[1]= (addroffest>>16)&0x000000ff;
        buf[2]= (addroffest>>8)&0x000000ff;
        buf[3]= addroffest&0x000000ff;
        file.write(buf,4);

        rowdata =QString::number(addroffest);
        ui->tableWidget->item(i,1)->setText(rowdata);
        addroffest += Tempfile.size();
        bulidfile.write(Tempfile.readAll());
        Tempfile.close();

    }
   /* tmp.fill(0xff,FileDataStartAddr.toLongLong());
    file.write(tmp.data());
    tmp.clear();*/

    addroffest = FileDataStartAddr.toLongLong();
    file.seek(addroffest);
    bulidfile.flush();

    bulidfile.seek(0);

    if(!file.write(bulidfile.readAll()))
        QMessageBox::warning(this, tr("Filemake"),tr("无法生成数据文件"));
    file.close();

    bulidfile.remove();
    bulidfile.close();
}

void MainWindow::on_actionGug_triggered()
{
    Dialogabout->show();
}
